package com.bijiawang.search.service;


import com.bijiawang.search.pojo.Goods;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.assertj.core.util.Arrays;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SearchTBSNService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RedisTemplate redisTemplate;

    @Async
    public Future<ArrayList<Goods>> SearchTaobao(String key) throws IOException {
        ValueOperations<String,ArrayList<Goods>> valueOperations = redisTemplate.opsForValue();
        ArrayList<Goods> List = valueOperations.get("Taobao" + key);
        if (List != null){
            return new AsyncResult<ArrayList<Goods>>(List);
        }else {
            String newKey = key.replace(" ", "");
            HttpGet httpget = new HttpGet("https://s.taobao.com/search?q=" + newKey);
            logger.info("Downloading {}", httpget.getURI());
            BasicCookieStore cookieStore = new BasicCookieStore();

            String cooke = "thw=cn\n" +
                    "_l_g_=Ug%3D%3D\n" +
                    "lgc=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                    "JSESSIONID=3C7792C84C488180260F5CF5528F85DA\n" +
                    "cookie1=BqqsV5w12UE9coppvhZDGVG47yyCtdvd0lAk0cs5bRc%3D\n" +
                    "existShop=MTU4ODY1MDY4MA%3D%3D\n" +
                    "cookie2=124a3f0ec692d78f35af4388d6ea7468\n" +
                    "sg=800\n" +
                    "cna=qdA3F7qoSl8CAWUuOFxf7lC/\n" +
                    "enc=yy6hFBs6UpM0HVpzY0LPxfuiMyLrVfMtP4VLEc3o%2BEmJJ2AdfEvHLadoftgQns%2FVoepwFLBLjs7n1PRrrYyvXQ%3D%3D\n" +
                    "skt=edd3c255dcd5bcad\n" +
                    "_tb_token_=e5a5740eeefeb\n" +
                    "hng=CN%7Czh-CN%7CCNY%7C156\n" +
                    "dnk=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                    "uc1=cookie16=V32FPkk%2FxXMk5UvIbNtImtMfJQ%3D%3D&cookie21=WqG3DMC9Edo1TBf%2BcZ0sSw%3D%3D&cookie15=URm48syIIVrSKA%3D%3D&existShop=true&pas=0&cookie14=UoTUMtablXWHqQ%3D%3D\n" +
                    "uc3=id2=UUwZ%2B8mWCONfGg%3D%3D&lg2=WqG3DMC9VAQiUQ%3D%3D&vt3=F8dBxGXOk%2F9DxsCTSLg%3D&nk2=qA%2BbFW21LXj0o2DlxBf7zm0%3D\n" +
                    "tracknick=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                    "mt=ci=36_1\n" +
                    "uc4=nk4=0%40qjTPOqEF1KIICVgm3StKALPXz%2BgeF7cCxbCE%2BQ%3D%3D&id4=0%40U27Giqeot4nzy8oKfJP9k0Fd7485\n" +
                    "unb=2496317690\n" +
                    "tfstk=cVKcBMvHCE7j9XLXd-sXB5UdHCDRZPePMCRX4nybWifGyHKPiIzz80Ftr_ADXP1..\n" +
                    "_samesite_flag_=true\n" +
                    "l=eBxO_A0mQkNZc1PoXOfaFurza77OSIRYYuPzaNbMiT5P9JCB5PECWZbY3r86C3Gch6JpR3vn1-hMBeYBq7Vonxv92j-la_kmn\n" +
                    "_cc_=U%2BGCWk%2F7og%3D%3D\n" +
                    "cookie17=UUwZ%2B8mWCONfGg%3D%3D\n" +
                    "_nk_=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                    "sgcookie=ELsxJfA46ruJnPZ0PfKzn\n" +
                    "t=0c838e8ffb9d9068dca307c5a8c6a15e\n" +
                    "v=0\n" +
                    "csg=2a4d1c24\n" +
                    "isg=BG9vMGEfbVavZ2lqk9UGSBel_oN5FMM2_774woH8C17l0I_SieRThm0CVsFuqJuu";

            String[] split = cooke.split("\n");

            for (int i = 0; i <= 30; i++) {
                String[] split1 = split[i].split("=");
                BasicClientCookie cookie = new BasicClientCookie(split1[0], split1[1]);
                cookie.setAttribute(ClientCookie.PATH_ATTR, "/");
                cookie.setAttribute(ClientCookie.EXPIRES_ATTR, null);
                cookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".taobao.com");
                cookie.setAttribute(ClientCookie.SECURE_ATTR, "false");
                cookie.setPath("/");
                cookie.setExpiryDate(null);
                cookie.setDomain(".taobao.com");
                cookie.setSecure(false);
                cookieStore.addCookie(cookie);
            }

            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            CloseableHttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity, "utf-8");

            Document doc = Jsoup.parse(content);
            Elements script = doc.getElementsByTag("script");
            if (script.size() >7) {
                Element element = script.get(7);
                String data = element.data();

                Pattern compile = Pattern.compile("\"raw_title\":\"(.*?)\""); //标题
                Matcher GoodNames = compile.matcher(data);

                Pattern ImageUri1 = Pattern.compile("\"pic_url\":\"(.*?)\"");//图片链接
                Matcher ImageUri = ImageUri1.matcher(data);
//
                Pattern compile1 = Pattern.compile("\"detail_url\":\"(.*?)\",");//商品链接
                Matcher GoodsUri = compile1.matcher(data);

                Pattern compile2 = Pattern.compile("\"view_price\":\"(.*?)\",");//价格
                Matcher price = compile2.matcher(data);

                Pattern compile3 = Pattern.compile("\"nick\":\"(.*?)\",\"sho");
                Matcher shopname = compile3.matcher(data);

                ArrayList<Goods> goodsArrayList = new ArrayList<>();
                for (; price.find(); ) {
                    Goods goods = new Goods();
                    GoodsUri.find();
                    ImageUri.find();
                    GoodNames.find();
                    shopname.find();

                    String ret = GoodsUri.group(1);
                    String replace = ret.replace("\\u003d", "=").replace("\\u0026", "&");
                    goods.setGoodsUri(replace);

                    String ret1 = GoodNames.group(1);
                    goods.setGoodsName(ret1);

                    String ret2 = ImageUri.group(1);
                    goods.setImageUri(ret2);

                    String ret3 = price.group(1);
                    goods.setPrice("￥" + ret3);

                    goods.setPlatform("淘宝");

                    String group = shopname.group(1);
                    goods.setShopName(group);
                    goodsArrayList.add(goods);

                }

                response.close(); // response关闭
                httpClient.close(); // httpClient关闭
                logger.info("Success downloading {}", httpget.getURI());
                valueOperations.set("Taobao" + key, goodsArrayList, 35, TimeUnit.MINUTES);
                return new AsyncResult<ArrayList<Goods>>(goodsArrayList);
            }else {
                ArrayList<Goods> goodsArrayList = new ArrayList<>();
                logger.error("Error downloading {}", httpget.getURI());
                valueOperations.set("Taobao" + key, goodsArrayList, 5, TimeUnit.MINUTES);
                return new AsyncResult<ArrayList<Goods>>(goodsArrayList);
            }
        }
    }

    @Async
    public Future<ArrayList<Goods>> SearchSuNing(String key) throws IOException {
        ValueOperations<String,ArrayList<Goods>> valueOperations = redisTemplate.opsForValue();
        ArrayList<Goods> List = valueOperations.get("SuNing" + key);
        if (List != null){
            return new AsyncResult<ArrayList<Goods>>(List);
        }else {
            String newKey = key.replace(" ", "");
            HttpGet httpGet = new HttpGet("https://search.suning.com/" + newKey + "/");
            logger.info("Downloading {}", httpGet.getURI());
            CloseableHttpClient build = HttpClients.custom().build();
            CloseableHttpResponse execute = build.execute(httpGet);
            HttpEntity entity = execute.getEntity();
            String content = EntityUtils.toString(entity, "utf-8");
            Document parse = Jsoup.parse(content);

            Elements general_clearfix = parse.getElementsByClass("general clearfix");
            String data = general_clearfix.toString();
            Pattern compile = Pattern.compile("<img alt=\"(.*?)\" src=\"");
            Matcher GoodsName = compile.matcher(data);//
            Pattern compile1 = Pattern.compile("src=\"(.*?)\" picPrio");
            Matcher imageUri = compile1.matcher(data);
            ArrayList<Goods> goodsArrayList = new ArrayList<>();
            for (; GoodsName.find(); ) {//标题和Uri
                imageUri.find();
                Goods goods = new Goods();
                goods.setGoodsName(GoodsName.group(1));
                goods.setImageUri(imageUri.group(1));
                goods.setPlatform("苏宁易购");
                goodsArrayList.add(goods);
            }

            ArrayList<String> list = new ArrayList<>();
            ArrayList<String> GoodsUris = new ArrayList<>();
            ArrayList<String> Goodsprices = new ArrayList<>();
            Elements priceClass = parse.getElementsByClass("def-price");
            String uri = "";
            String GoodsUri = "";
            for (Element a : priceClass) {//获取关键字符并拼串
                String datasku = a.attr("datasku");
                String brand_id = a.attr("brand_id");
                String mdmgroupid = a.attr("mdmgroupid");
                String[] split = datasku.split("\\|.*\\|");
                if (split[1].equals("0000000000")) {
                    uri = split[0] + "_____" + mdmgroupid + "_" + brand_id;
                    GoodsUri = "https://product.suning.com/0000000000/" + split[0] + ".html";
                } else {
                    uri = split[0] + "__2_" + split[1] + "_" + mdmgroupid + "_" + brand_id;
                    GoodsUri = "https://product.suning.com/" + split[1] + "/" + split[0] + ".html";
                }
                GoodsUris.add(GoodsUri);
                list.add(uri);
            }

            ArrayList<String> Uri = new ArrayList<>();
            for (int i = 0; i <= 2; i++) {//拼串
                uri = "";
                for (int j = i * 10; j <= i * 10 + 9; j++) {
                    if (j == i * 10 + 9) {
                        uri += list.get(j);
                        continue;
                    }
                    uri += list.get(j) + ",";
                }
                String uri1 = "https://ds.suning.com/ds/generalForTile/" + uri + "-020-2-0000000000-1--ds0000000005860.jsonp";
                Uri.add(uri1);
            }

            for (int i = 0; i <= 2; i++) {//价格
                String s = SearchTBSNService.sendGet(Uri.get(i));
                Pattern compile2 = Pattern.compile("\"price\":\"(.*?)\"");
                Matcher matcher = compile2.matcher(s);
                while (matcher.find()) {
                    if(matcher.group(1).equals("")){
                        Goodsprices.add("9999.99");
                    }else {
                        Goodsprices.add(matcher.group(1));
                    }
                }
            }

            Elements Shop = parse.getElementsByClass("store-stock");//店铺

            for (int i = 0; i < GoodsUris.size(); i++) {
                goodsArrayList.get(i).setGoodsUri(GoodsUris.get(i));
                goodsArrayList.get(i).setPrice("￥" + Goodsprices.get(i));
                goodsArrayList.get(i).setShopName(Shop.get(i).text());
            }

            execute.close();
            build.close();
            logger.info("Success downloading {}", httpGet.getURI());
            valueOperations.set("SuNing" + key,goodsArrayList,38, TimeUnit.MINUTES);
            return new AsyncResult<ArrayList<Goods>>(goodsArrayList);
        }

    }

    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public String SearchTaobaoOne(String key) throws IOException {
        String newKey = key.replace(" ", "");
        HttpGet httpget = new HttpGet("https://s.taobao.com/search?q=" + newKey);
        BasicCookieStore cookieStore = new BasicCookieStore();
        String cooke = "thw=cn\n" +
                "_l_g_=Ug%3D%3D\n" +
                "lgc=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                "JSESSIONID=3C7792C84C488180260F5CF5528F85DA\n" +
                "cookie1=BqqsV5w12UE9coppvhZDGVG47yyCtdvd0lAk0cs5bRc%3D\n" +
                "existShop=MTU4ODY1MDY4MA%3D%3D\n" +
                "cookie2=124a3f0ec692d78f35af4388d6ea7468\n" +
                "sg=800\n" +
                "cna=qdA3F7qoSl8CAWUuOFxf7lC/\n" +
                "enc=yy6hFBs6UpM0HVpzY0LPxfuiMyLrVfMtP4VLEc3o%2BEmJJ2AdfEvHLadoftgQns%2FVoepwFLBLjs7n1PRrrYyvXQ%3D%3D\n" +
                "skt=edd3c255dcd5bcad\n" +
                "_tb_token_=e5a5740eeefeb\n" +
                "hng=CN%7Czh-CN%7CCNY%7C156\n" +
                "dnk=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                "uc1=cookie16=V32FPkk%2FxXMk5UvIbNtImtMfJQ%3D%3D&cookie21=WqG3DMC9Edo1TBf%2BcZ0sSw%3D%3D&cookie15=URm48syIIVrSKA%3D%3D&existShop=true&pas=0&cookie14=UoTUMtablXWHqQ%3D%3D\n" +
                "uc3=id2=UUwZ%2B8mWCONfGg%3D%3D&lg2=WqG3DMC9VAQiUQ%3D%3D&vt3=F8dBxGXOk%2F9DxsCTSLg%3D&nk2=qA%2BbFW21LXj0o2DlxBf7zm0%3D\n" +
                "tracknick=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                "mt=ci=36_1\n" +
                "uc4=nk4=0%40qjTPOqEF1KIICVgm3StKALPXz%2BgeF7cCxbCE%2BQ%3D%3D&id4=0%40U27Giqeot4nzy8oKfJP9k0Fd7485\n" +
                "unb=2496317690\n" +
                "tfstk=cVKcBMvHCE7j9XLXd-sXB5UdHCDRZPePMCRX4nybWifGyHKPiIzz80Ftr_ADXP1..\n" +
                "_samesite_flag_=true\n" +
                "l=eBxO_A0mQkNZc1PoXOfaFurza77OSIRYYuPzaNbMiT5P9JCB5PECWZbY3r86C3Gch6JpR3vn1-hMBeYBq7Vonxv92j-la_kmn\n" +
                "_cc_=U%2BGCWk%2F7og%3D%3D\n" +
                "cookie17=UUwZ%2B8mWCONfGg%3D%3D\n" +
                "_nk_=%5Cu5E05%5Cu5230%5Cu5929%5Cu5D29%5Cu5730%5Cu88C212138\n" +
                "sgcookie=ELsxJfA46ruJnPZ0PfKzn\n" +
                "t=0c838e8ffb9d9068dca307c5a8c6a15e\n" +
                "v=0\n" +
                "csg=2a4d1c24\n" +
                "isg=BG9vMGEfbVavZ2lqk9UGSBel_oN5FMM2_774woH8C17l0I_SieRThm0CVsFuqJuu";

        String[] split = cooke.split("\n");

        for (int i = 0; i <= 30; i++) {
            String[] split1 = split[i].split("=");
            BasicClientCookie cookie = new BasicClientCookie(split1[0], split1[1]);
            cookie.setAttribute(ClientCookie.PATH_ATTR, "/");
            cookie.setAttribute(ClientCookie.EXPIRES_ATTR, null);
            cookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".taobao.com");
            cookie.setAttribute(ClientCookie.SECURE_ATTR, "false");
            cookie.setPath("/");
            cookie.setExpiryDate(null);
            cookie.setDomain(".taobao.com");
            cookie.setSecure(false);
            cookieStore.addCookie(cookie);
        }

        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        Document doc = Jsoup.parse(content);

        Elements script = doc.getElementsByTag("script");
        String price1 = "";
        if (script.size() > 7) {
            Element element = script.get(7);
            String data = element.data();

            Pattern compile2 = Pattern.compile("\"view_price\":\"(.*?)\",");//价格
            Matcher price = compile2.matcher(data);

            while (price.find()){
                price1 = price.group(1);
            }
        }
        response.close(); // response关闭
        httpClient.close(); // httpClient关闭
        return price1;
    }

    public String SearchSuNingOne(String key) throws IOException {
        String newKey = key.replace(" ", "");
        HttpGet httpGet = new HttpGet("https://search.suning.com/" + newKey + "/");
        CloseableHttpClient build = HttpClients.custom().build();
        CloseableHttpResponse execute = build.execute(httpGet);
        HttpEntity entity = execute.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        Document parse = Jsoup.parse(content);

        Elements priceClass = parse.getElementsByClass("def-price");
        Element a = priceClass.get(0);
        String uri = "";
        String GoodsUri = "";
        //获取关键字符并拼串
        String datasku = a.attr("datasku");
        String brand_id = a.attr("brand_id");
        String mdmgroupid = a.attr("mdmgroupid");
        String[] split = datasku.split("\\|.*\\|");
        if (split[1].equals("0000000000")) {
            uri = split[0] + "_____" + mdmgroupid + "_" + brand_id;
        } else {
            uri = split[0] + "__2_" + split[1] + "_" + mdmgroupid + "_" + brand_id;
        }
        String uri1 = "https://ds.suning.com/ds/generalForTile/" + uri + "-020-2-0000000000-1--ds0000000005860.jsonp";
        String s = SearchTBSNService.sendGet(uri1);
        Pattern compile2 = Pattern.compile("\"price\":\"(.*?)\"");
        Matcher matcher = compile2.matcher(s);
        String price = "";
        while (matcher.find()) {
            price = matcher.group(1);
        }
        execute.close();
        build.close();
        return price;
    }
}


